﻿// Required Modules
var express = require("express");//核心包
var morgan = require("morgan");
var bodyParser = require("body-parser");
var jwt = require("jsonwebtoken");
var mongoose = require("mongoose");//使用 mongoose 操作数据库
var redis = require("redis");//同时使用 redis 操作数据库
var helmet = require('helmet');//导入helmet
var restful = require('./restful/api');

var connectMongoDB = function () {
    var dbUrl = process.env.MONGO_URL || 'mongodb://127.0.0.1:27017/test',//数据库地址
        db = mongoose.createConnection(dbUrl);//尝试连接数据库

    db.on('connect', function (res) {
        console.log(' mongodb connected successful!');
    });
    db.on('error', function (error) {
        console.log(' mongodb database connect failed ' + error);
    });

    return db;
};

var connectRedis = function () {
    var RDS_PORT = 6379,        //端口号
        RDS_HOST = '127.0.0.1',    //服务器IP
        RDS_OPTS = {},            //设置项
        client = redis.createClient(RDS_PORT, RDS_HOST, RDS_OPTS);

    client.on('connect', function (err) {
        console.log(' redis connected successful!');
    });
    client.on("error", function (err) {
        console.log(' redis database connect failed ' + error);
    });

    return client;
};

var setHead = function (app) {
    app.use(bodyParser.urlencoded({extended: true}));
    app.use(bodyParser.json());
    app.use(morgan("dev"));
    app.use(function (req, res, next) {//解决跨域访问问题
        res.setHeader('Access-Control-Allow-Origin', '*');
        res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE');
        res.setHeader('Access-Control-Max-Age', '3600');
        res.setHeader('Access-Control-Allow-Headers',
            'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With');
        next();
    });
    app.use(helmet());//保护请求头信息
};

module.exports = function () {

    var app = express();

    return {
        'build': function () {

            app.use(express.static("./app"));
            app.get("/", function (req, res) {
                res.sendFile("./app/index.html");
            });

            // Start Server
            var port = process.env.PORT || 3000;
            app.listen(port, function () {
                console.log('prepared to start the build project...');
                console.log("Express server listening on port " + port);
            });
        },
        'develop': function () {

            app.use(express.static("./app"));
            app.get("/", function (req, res) {
                res.sendFile("./app/index.html");
            });

            var port = process.env.PORT || 3002;
            // Start Server
            app.listen(port, function () {
                console.log('prepared to start the developing project...');
                console.log("Express server listening on port " + port);
            });
        },
        'restful': function () {
            connectMongoDB();//连接数据库
            connectRedis();
            setHead(app);//设置请求头信息
            restful(app);//获取提供的result接口

            // Start Server
            var port = process.env.PORT || 3004;//指定端口
            app.listen(port, function () {
                console.log("restful server starting...");
                console.log("Express server listening on port " + port);
            });

            process.on('uncaughtException', function (err) {
                if (err.code === 'EADDRINUSE') {
                    console.log('Port: ' + err.port + ' EADDRINUSE');
                } else {
                    console.log(err);
                }
            });
        }
    }
};
